from atm_oop.utility_class import Utility

class User:
    login_name = ''
    def __init__(self):
        self.utility = Utility()
        self.menu = None

    # 检查用户是否存在
    def check_name(self,username):
        result = self.utility.query_one("select username from user_info where username = '%s'" % username)
        if result != None:
            return True
        else:
            return False

    # 输入用户名
    def input_name(self):
        username = input("[注册]请输入用户名：")
        if self.check_name(username):
            print("用户名已存在")
            return self.input_name()
        else:
            return username

    # 输入密码
    def input_password(self):
        password = input("[注册]请输入密码：")
        if len(password) < 5:
            print("你输入的密码过短.")
            return self.input_password()
        else:
            return password

    # 校验电话号码
    def check_phone(self,phone):
        isphone = True
        if len(phone) > 11:
            isphone = False
        for i in range(0, len(phone)):
            if ord(phone[i]) < 48 or ord(phone[i]) > 57:
                isphone = False
                break
        if isphone == False:
            return False
        else:
            return True

    # 输入电话号码
    def input_phone(self):
        phone = input("[注册]请输入手机号码：")
        if self.check_phone(phone):
            return phone
        else:
            return self.input_phone

    # 注册
    def reg(self):
        from atm_oop.menu_class import Menu
        username = self.input_name()
        password = self.input_password()
        phone = self.input_phone()
        sql = "insert into user_info values ('%s','%s','%s',0)" %(username,password,phone)
        self.utility.db_operation(sql)
        print("注册成功")
        self.menu = Menu()
        self.menu.start_menu()

    # 登录
    def login(self):
        from atm_oop.menu_class import Menu
        username = input("[登录]请输入用户名：")
        pwd = input("[登录]请输入密码：")
        result = self.utility.query_one("select password from user_info where username = '%s'" %username)
        if result != None:
            if result[0] == pwd:
                print("登录成功")
                User.login_name = username
                self.menu = Menu()
                self.menu.main_menu()
            else:
                print("密码错误")
                self.menu.start_menu()
        else:
            print("用户不存在")
            self.login()

    # 修改密码
    def update_pwd(self):
        from atm_oop.menu_class import Menu
        while '1' == '1':
            new_pwd1 = input("请输入新密码：")
            new_pwd2 = input("请重复输入新密码：")
            if new_pwd1 == new_pwd2:
                break
        self.utility.db_operation("update user_info set password = '%s' where username = '%s'" %(new_pwd1,User.login_name))
        print("修改密码成功")
        self.menu = Menu()
        self.menu.main_menu()

if __name__ == '__main__':
    user = User()
    print(user.check_phone('12341'))